import React, { Component } from 'react';
import { View, Text, StyleSheet, Animated, PixelRatio, Dimensions} from 'react-native';
import PropTypes from "prop-types";

function getUIPt(px) {
    const { width } = Dimensions.get('window');
    return PixelRatio.roundToNearestPixel((px * width) / 750);
}
const FlatListState = {
    IDLE:0,
    LoadMore:1,
    Refreshing:2
}
class StickList extends Component {
    scrollY = new Animated.Value(0)

    constructor(props) {
        super(props);
        this.state = {
            listHeight: 0,
            isWideScreen: false
        };
       
    }

    setIsWideScreen = () => {
        this.init()

        const screenWidth = Dimensions.get('window').width;
        if (screenWidth) {
            this.setState({
                isWideScreen: screenWidth > 500 && screenWidth < 800
            })
        }
    }

    renderItem = (item) => {
        return this.props.renderItem(item);
    }

    componentDidMount() {
        this.init()
        // 适配鸿蒙折叠屏动态更新组件
        this.addEventListenerScreenWidth = Dimensions.addEventListener('change', this.setIsWideScreen)
    }

    init=()=>{
        if(this.props.data){
            this.setState({
                list:[...this.props.data],
                topIndexList:[...this.props.topIndexList]
            })
        }
     
    }
    componentWillUnmount() {
       
    }
    
    onEndReached=()=>{

        if(typeof this.props.refreshing =="boolean" || this.props.data.length==0){
            return
        }
        if(!this.props.pageSize){
            console.warn("PageSize must be set");
            return
        }

        if(this.props.data.length && this.props.pageSize !==0){
            return
        }

        if(this.props.refreshing ==FlatListState.IDLE){

            this.props.onEndReached&&this.props.onEndReached()

        }



    }



    renderFooter=()=>{
        
        if( this.props.renderFooter){
            return this.props.renderFooter()
        }
        return null
    }
    render() {
        const {
            data:list,topIndexList,
            onEndReachedThreshold,
            scrollEventThrottle,
            showsVerticalScrollIndicator,
            ListEmptyComponent,
            ItemSeparatorComponent
             } = this.props

        let refreshing = false

        let emptyContent = null

        let separatorComponent = null

        if(ListEmptyComponent){

            emptyContent = React.isValidElement(ListEmptyComponent)?ListEmptyComponent:<ListEmptyComponent/>

        }else {

            emptyContent = <Text style={styles.emptyText}>暂无数据下拉刷新 </Text>

        }

        if(ItemSeparatorComponent){

            separatorComponent =  React.isValidElement(ItemSeparatorComponent)?ItemSeparatorComponent:<ItemSeparatorComponent/>

        }else {

            separatorComponent = <View style={{height:1,backgroundColor:"#D6D6D6"}} />

        }

        if(typeof this.props.refreshing == "number"){
            if(this.props.refreshing == FlatListState.Refreshing){
                refreshing = true
            }else  if(typeof this.props.refreshing == "boolean"){
                refreshing =  this.props.refreshing
            }else if(typeof this.props.refreshing == "undefined"){
                refreshing = false
            }
        }
        let containerStyle = styles.container
        if(this.props.containerStyle){
            containerStyle={...containerStyle,...this.props.containerStyle}
        }
        
        return (
           <View style={containerStyle}>
                
                { (!!list && list.length > 0&& (
                    <Animated.FlatList
                   
                        onLayout={(e)=>{
                            let height = e.nativeEvent.layout.height
                            if(this.state.listHeight<height){
                                this.setState({listHeight:height})
                            }
                        }}
                        contentContainerStyle={styles.FlatListContainer}
                        data={list}
                        ListFooterComponent={() => this.renderFooter()}
                        renderItem={this.renderItem}
                        keyExtractor={(item, index) => index}
                        showsVerticalScrollIndicator={showsVerticalScrollIndicator}
                        stickyHeaderIndices={topIndexList}
                        scrollEventThrottle={scrollEventThrottle}
                        onEndReached={() => { this.onEndReached(); }}
                        refreshing={refreshing}
                        onRefresh={this.onRefresh}
                        onEndReachedThreshold={onEndReachedThreshold ||0.1}
                        ItemSeparatorComponent={()=>separatorComponent}
                        ListEmptyComponent={
                            ()=><View style={{height:this.state.listHeight,width:"100%",alignItems:"center" , justifyContent:"center"}}>
                                {emptyContent}
                            </View>
                        }
                        onScroll={
                            Animated.event(
                                [
                                    {
                                        nativeEvent: {
                                            contentOffset: { y: this.scrollY },
                                        },
                                    },
                                ],
                                {
                                    useNativeDriver: true,


                                }
                            )
                          
                        }
                        {...this.props}
                    />
                ))} 
           </View>
        );
    }

    onRefresh=()=>{
      if((typeof this.props.refreshing == "boolean"&& !this.props.refreshing) ||
       typeof this.props.refreshing == "number" && this.props.refreshing!==FlatListState.LoadMore && 
       this.props.refreshing !==FlatListState.Refreshing){
            this.props.onRefresh&& this.props.onRefresh()
      }
    }
}

export default StickList;
StickList.propTypes = {
    data: PropTypes.array.isRequired,
    onEndReached:PropTypes.func,
    topIndexList: PropTypes.array,
    renderFooter:PropTypes.func,
    renderItem:PropTypes.func,
    refreshing:PropTypes.oneOfType([PropTypes.bool,PropTypes.number]),
    containerStyle:PropTypes.object
}
const styles = StyleSheet.create({
    container:{
      
    },
    FlatListContainer: {
        paddingBottom: getUIPt(80),
    },
    emptyText:{
        fontSize:17,
        color:"#6666"
    }
})